package tracker;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MonitorVehicleTracker implements VehicleTracker {
    private final Map<String, Point> locations;

    public MonitorVehicleTracker(Map<String, Point> locations) {
        this.locations = deepCopy(locations);
    }

    public synchronized Map<String, Point> getLocations() {
        return deepCopy(locations);
    }

    public synchronized Point getLocation(String id) {
        Point loc = locations.get(id);
        return loc == null ? null : new SimplePoint(loc);
    }

    public synchronized void setLocation(String id, int x, int y) {
        Point loc = locations.get(id);
        if (loc == null)
            throw new IllegalArgumentException("No such ID: " + id);
        loc.setX(x);
        loc.setY(y);
    }

    private static Map<String, Point> deepCopy(Map<String, Point> m) {
        Map<String, Point> result = new HashMap<String, Point>();
        for (String id : m.keySet()) {
            result.put(id, new SimplePoint(m.get(id)));
        }
        return Collections.unmodifiableMap(result);
    }
}
